package vip.xiaonuo.biz.modular.eduimg.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.noear.folkmq.client.MqConsumeHandler;
import org.noear.folkmq.client.MqMessageReceived;
import org.springframework.stereotype.Component;
import vip.xiaonuo.biz.core.enums.MQTopic;
import vip.xiaonuo.biz.modular.eduimg.entity.EduImg;
import vip.xiaonuo.biz.modular.eduimg.mapper.EduImgMapper;
import vip.xiaonuo.biz.modular.eduimggroup.entity.EduImgGroup;
import vip.xiaonuo.biz.modular.eduimggroup.mapper.EduImgGroupMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component(MQTopic.IMAGE_GROUP_COUNT)
public class ImageGroupCountListener implements MqConsumeHandler {

    @Resource
    EduImgGroupMapper eduImgGroupMapper;
    @Resource
    EduImgMapper eduImgMapper;

    @Override
    public void consume(MqMessageReceived message) throws Exception {
        log.info("{}: group={}, message={}",MQTopic.IMAGE_GROUP_COUNT,message.getConsumerGroup(),message.getBodyAsString());

        List<String> groupIds = JSON.parseObject(message.getBodyAsString(), new TypeReference<List<String>>() {});
        List<EduImgGroup> groups = eduImgGroupMapper.selectBatchIds(groupIds);
        for (EduImgGroup group : groups) {
            ArrayList<String> groupFullPath = new ArrayList<>();
            groupFullPath.addAll(group.getParentPath());
            groupFullPath.add(group.getId());
            String groupFullPathStr = groupFullPath.parallelStream().map(s -> "'" + s + "'").collect(Collectors.joining(","));

            QueryWrapper<EduImg> wrapper = new QueryWrapper<>();
            wrapper.apply("img_group_path = ARRAY["+groupFullPathStr+"]::varchar[]");
            Long count = eduImgMapper.selectCount(wrapper);
            eduImgGroupMapper.update(new LambdaUpdateWrapper<EduImgGroup>()
                    .eq(EduImgGroup::getId, group.getId())
                    .set(EduImgGroup::getImgCount, count)
            );
        }


    }
}
